<?php
namespace App\Models\DyModels;
use App\Models\ParentModel;
use DB;
use Illuminate\Support\Facades\Redis;
/**
 * 抖音处理视频表model
 * @author puppet
 */
class Douyin extends ParentModel{
	/**
	* 与模型关联的数据表。
	*
	* @var string
	*/
	protected $table = 'pt_dy_access_token';

	/**
	* DB::直接操作的数据库表名
	* @var string
	*/
	protected $db_table = 'pt_dy_access_token';

	/**
	* 主键 默认id。
	*
	* @var string
	*/
	protected $primaryKey = 'id';

	/**
	* 指定是否模型应该被戳记时间。
	*
	* @var bool
	*/
	public $timestamps = false;
	
	//添加或者更新合伙人、会员授权信息
	function saveToken($arr,$scope,$open_id){
		$old=$this->userTokenInfo($open_id);
		$data=array(
			'access_token'=>isset($arr['access_token']) ? $arr['access_token'] : '',
			'description'=>isset($arr['description']) ? $arr['description'] : '',
			'error_code'=>isset($arr['error_code']) ? $arr['error_code'] : '',
			'expires_in'=>isset($arr['expires_in']) ? $arr['expires_in'] : '',
			'refresh_expires_in'=>isset($arr['refresh_expires_in']) ? $arr['refresh_expires_in'] : '',
			'refresh_token'=>isset($arr['refresh_token']) ? $arr['refresh_token'] : '',
			'scope'=>$scope,
			'update_time'=>date('Y-m-d H:i:s',time()),
			'status'=>1,
		);
		
		if($old){//修改
			$sql="update {$this->table} set ";
			foreach($data as $k=>$v){
				$sql.="`{$k}`='{$v}',";
			}
			$sql=substr($sql,0,-1)." where id={$old}";
			DB::update($sql);
		}else{//添加
			$data['open_id']=$open_id;
			$data['create_time']=date('Y-m-d H:i:s',time());
			DB::table($this->table)->insertGetId($data);
		}
	}
	
	//获取用户授权信息
	function userTokenInfo($open_id){
		$values=[$open_id];
		$sql="select id from {$this->table} where open_id = ?";
		$re=DB::select($sql,$values);
		return (isset($re[0]) ? $re[0]['id'] : false);
	}
	
	//更新会员、合伙人用户信息
	function upUserInfo($arr,$open_id,$partner_id){
		$values=[$partner_id,$open_id];
		$sql="select id from pt_user where partner_id = ? and open_id = ?  ";
		$re=DB::select($sql,$values);
		$re=isset($re[0]) ? $re[0]['id'] : false;
		$e_account_role="普通用户";$gender='未知';
		if(isset($arr['e_account_role']) && $arr['e_account_role']=='EAccountM'){
			$e_account_role="普通企业号";
		}elseif(isset($arr['e_account_role']) && $arr['e_account_role']=='EAccountS'){
			$e_account_role="认证企业号";
		}elseif(isset($arr['e_account_role']) && $arr['e_account_role']=='EAccountK'){
			$e_account_role="品牌企业号";
		}
		if(isset($arr['gender']) && $arr['gender']==1){
			$gender="男";
		}elseif(isset($arr['gender']) && $arr['gender']==2){
			$gender="女";
		}
		$data=array(
			'province'=>isset($arr['province']) ? $arr['province'] : '',
			'union_id'=>isset($arr['union_id']) ? $arr['union_id'] : '',
			'avatar'=>isset($arr['avatar']) ? $arr['avatar'] : '',
			'e_account_role'=>$e_account_role,
			'error_code'=>isset($arr['error_code']) ? $arr['error_code'] : '',
			'nickname'=>isset($arr['nickname']) ? htmlspecialchars($arr['nickname'],ENT_QUOTES) : '',
			'city'=>isset($arr['city']) ? $arr['city'] : '',
			'country'=>isset($arr['country']) ? $arr['country'] : '',
			'description'=>isset($arr['description']) ? $arr['description'] : '',
			'gender'=>$gender,
			'update_time'=>date('Y-m-d H:i:s',time()),
            'status'=>1,
		);
		if($re){
			$sql="update pt_user set ";
			foreach($data as $k=>$v){
				$sql.="`{$k}`='{$v}',";
			}
			$sql=substr($sql,0,-1)." where id={$re}";
			return DB::update($sql);
		}else{
			$data['partner_id']=$partner_id;
			$data['open_id']=$open_id;
			$data['create_time']=date('Y-m-d H:i:s',time());
			return DB::table("pt_user")->insertGetId($data);
		}
	}
	
	
	//插入更新达人信息------------------------------------------------------------------------------------------------------------------------------------------
	function upUserInfoTwo($arr,$open_id,$kid,$industry_id){
		$sql="select id from pt_talent where open_id = ? and (tl_status=1 or tl_status=0)";
		$re=DB::select($sql,[$open_id]);
		$re=isset($re[0]) ? $re[0]['id'] : false;
		$tl_u_type="普通用户";$gender='未知';
		if(isset($arr['e_account_role']) && $arr['e_account_role']=='EAccountM'){
			$e_account_role="普通企业号";
		}elseif(isset($arr['e_account_role']) && $arr['e_account_role']=='EAccountS'){
			$e_account_role="认证企业号";
		}elseif(isset($arr['e_account_role']) && $arr['e_account_role']=='EAccountK'){
			$e_account_role="品牌企业号";
		}
		if(isset($arr['gender']) && $arr['gender']==1){
			$gender="男";
		}elseif(isset($arr['gender']) && $arr['gender']==2){
			$gender="女";
		}
		$data=array(
			'tl_uimg'=>isset($arr['avatar']) ? $arr['avatar'] : '',
			'tl_u_type'=>$tl_u_type,
			'tl_uname'=>isset($arr['nickname']) ? htmlspecialchars($arr['nickname'],ENT_QUOTES) : '',
			'gender'=>$gender,
			'tl_update'=>date('Y-m-d H:i:s',time()),
			'tl_auth'=>1,
			'tl_status'=>1,
		);
		if($industry_id){
			$data['tl_type']=$industry_id;
		}
		if($re){
			DB::table("pt_talent")->where("id",$kid)->update(["tl_status"=>-1]);
			
			$sql="update pt_talent set ";
			foreach($data as $k=>$v){
				$sql.="`{$k}`='{$v}',";
			}
			$sql=substr($sql,0,-1)." where id={$re}";
			return DB::update($sql);
		}else{
			$data['open_id']=$open_id;
			$data['tl_created']=date('Y-m-d H:i:s',time());
			
			$sql="select id from pt_talent where id=?";
			$re=DB::select($sql,[$kid]);
			$re=isset($re[0]['id']) ? $re[0]['id'] : false;
			
			if($re){
				$sql="update pt_talent set ";
				foreach($data as $k=>$v){
					$sql.="`{$k}`='{$v}',";
				}
				$sql=substr($sql,0,-1)." where id={$re}";
				return DB::update($sql);
			}else{
				return DB::table("pt_talent")->insertGetId($data);
			}
		}
	}
	
	
	
	
	//查询行业--------------------------------------------------------------------------------------------------------------------------------------------------
	function selectIndAll(){
		$values=[1];
		$sql="select name from pt_industry where status = ?";
		$re=DB::select($sql,$values);
		return isset($re[0]) ? $re : false;
	}
	//查询已授权的用户open_id \ token \ refresh_token  ---------------------------------------------------------------------------------------------------------------
	function selectAuthAll(){
		$sql="select open_id,access_token,refresh_token from {$this->table} where status = ? and access_token!='' and refresh_token!='' order by update_time desc limit 1";
		$re=DB::select($sql,[1]);
		return isset($re[0]) ? $re[0] : false;
	}
	
	//关键词视频入库
	function saveKeyVideo($arr,$keyword){
		if(isset($arr[0])){
                        $insertdata = array(); 
			foreach($arr as $k=>$v){
				$values=isset($v['share_url']) ? [$v['share_url']] : [''];
				$sql="select id from pt_keyword_video where share_url = ? limit 1";
				$re=DB::select($sql,$values);
				$re=isset($re[0]) ? $re[0]['id'] : false;
				$data = array(
					'cover'=>isset($v['cover']) ? $v['cover'] : '',
					'is_top'=>isset($v['is_top']) ? intval($v['is_top']) : 0,
					'is_reviewed'=>isset($v['is_reviewed']) ? intval($v['is_reviewed']) : 0,
					'digg_count'=>isset($v['statistics']['digg_count']) ? intval($v['statistics']['digg_count']) : 0,
					'download_count'=>isset($v['statistics']['download_count']) ? intval($v['statistics']['download_count']) : 0,
					'forward_count'=>isset($v['statistics']['forward_count']) ? intval($v['statistics']['forward_count']) : 0,
					'play_count'=>isset($v['statistics']['play_count']) ? intval($v['statistics']['play_count']) : 0,
					'share_count'=>isset($v['statistics']['share_count']) ? intval($v['statistics']['share_count']) : 0,
					'comment_count'=>isset($v['statistics']['comment_count']) ? intval($v['statistics']['comment_count']) : 0,
					'create_time'=>isset($v['create_time']) ? date('Y-m-d H:i:s',$v['create_time']) : '',
					'update_time'=>date('Y-m-d H:i:s',time()),
					'share_url'=>isset($v['share_url']) ? $v['share_url'] : '',
					'title'=>isset($v['title']) ? htmlspecialchars($v['title'],ENT_QUOTES) : '',
					'nickname'=>isset($v['nickname']) ? htmlspecialchars($v['nickname'],ENT_QUOTES) : '',
					'open_id'=>isset($v['open_id']) ? $v['open_id'] : '',
					'sec_item_id'=>isset($v['sec_item_id']) ? $v['sec_item_id'] : '',
					'video_id'=>$this->cut_str($v['share_url'],'/video/','/?',7),
					'item_id'=>isset($v['item_id']) ? $v['item_id'] : '',
				);
                                
				if($re){
					$sql="update pt_keyword_video set ";
					foreach($data as $k=>$v){
						$sql.="`{$k}`='{$v}',";
					}
					$sql=substr($sql,0,-1)." where id={$re}";
                                        DB::update($sql);
                                        
                                        //$redis::rpush('redislist_update' , $sql);  //存入redis队列中
                                        //echo  $redis::llen('videocachelist_update'); 
					
				}else{
					$data['keyword']=$keyword;
                                        $insertdata[] = $data;
                                        
                                        //$redis::rpush('redislist_add' , json_encode($data));//转成json格式 存入redis
					//DB::table("pt_keyword_video")->insertGetId($data);
                                        
				}
			}  
                        if(!empty($insertdata)){
                            DB::table("pt_keyword_video")->insert($insertdata);
                        }
		}
	}
        
        //定时任务入库操作
        function cacheSave(){
            $redis = new Redis();
            
            $len = $redis::llen("redislist_add"); 
            if($len > 0){//判断如果队列存在
                for($i=0;$i<$len;$i++){
                    $arr = $redis::rpop('redislist_add'); //data 移除队列里面最后的一个参数
                   
                    $data[] = json_decode($arr,true);
                }
                DB::table("pt_keyword_video")->insert($data); //批量插入
            }    
            
            
            $len = $redis::llen("redislist_update"); 
            if($len > 0){
                for($i=0;$i<$len;$i++){
                    $sql = $redis::rpop('redislist_update'); //返回sql
                    DB::update($sql);
                }
            }
       
        }






        /*截取指定位置字符串
	*	$str 要截取的字符串   $start 截取开始位置    $end 截取结束位置   $number 从第几个取   $fristStr 匹配字符串的位置
	*/
	function cut_str($str,$start,$end,$number){
		$fristStr=strpos($str,$start);
		if($fristStr===false){return false;}
		$sta=mb_substr($str,$fristStr+$number);
		return mb_substr($sta,0,strpos($sta,$end));
	}
	
	//更新token
	function upToken($arr,$open_id){
		$data=array(
			'access_token'=>isset($arr['access_token']) ? $arr['access_token'] : '',
			'refresh_token'=>isset($arr['refresh_token']) ? $arr['refresh_token'] : '',
			'scope'=>isset($arr['scope']) ? $arr['scope'] : '',
			'error_code'=>isset($arr['error_code']) ? $arr['error_code'] : '',
			'expires_in'=>isset($arr['expires_in']) ? $arr['expires_in'] : '',
			'refresh_expires_in'=>isset($arr['refresh_expires_in']) ? $arr['refresh_expires_in'] : '',
			'description'=>isset($arr['description']) ? $arr['description'] : '',
			'update_time'=>date('Y-m-d H:i:s',time()),
		);
		$sql="update pt_dy_access_token set ";
		foreach($data as $k=>$v){
			$sql.="`{$k}`='{$v}',";
		}
		$sql=substr($sql,0,-1)." where open_id='{$open_id}'";
		DB::update($sql);
	}
	//更新 refresh
	function upRef($arr,$open_id){
		$data=array(
			'refresh_expires_in'=>isset($arr['refresh_expires_in']) ? $arr['refresh_expires_in'] : '',
			'refresh_token'=>isset($arr['refresh_token']) ? $arr['refresh_token'] : '',
			'update_time'=>date('Y-m-d H:i:s',time()),
		);
		$sql="update pt_dy_access_token set ";
		foreach($data as $k=>$v){
			$sql.="`{$k}`='{$v}',";
		}
		$sql=substr($sql,0,-1)." where open_id='{$open_id}'";
		DB::update($sql);
	}
	//更改授权状态为0
	function upTokenStatus($open_id){
		$sql="update pt_dy_access_token set `status`=0 where open_id='{$open_id}'";
		DB::update($sql);
	}
	
	
	//视频评论入库-------------------------------------------------------------------------------------------------------------------------------------------------------------------------
	//查询未筛选的评论
	function selectCommentAll(){
		$sql="select * from pt_keyword_video_comment_all where 1=?";
		$re=DB::select($sql,[1]);
		return isset($re[0]) ? $re : false;
	}
	//更新、插入筛选后的评论------测试
	function upComment($data){
		$values=[$data['video_id'],$data['comment_id']];
		unset($data['id']);
		unset($data['json_text']);
		$re=DB::select("select id from pt_keyword_video_comment where video_id=? and comment_id=?",$values);
		$re=isset($re[0]) ? $re[0]['id'] : false;
		if($re){
			unset($data['video_id']);
			unset($data['comment_id']);
			$sql="update pt_keyword_video_comment set ";
			foreach($data as $k=>$v){
				$sql.="`{$k}`='{$v}',";
			}
			$sql=substr($sql,0,-1)." where id={$re}";
			DB::update($sql);
		}else{
			DB::table("pt_keyword_video_comment")->insertGetId($data);
		}
	}
	
	//插入未经过关键词筛选的评论
	function saveVideoCommentAll($data,$video_id,$comment_id){
		$values=[$video_id,$comment_id];
		$sql="select id from pt_keyword_video_comment_all where video_id = ? and comment_id = ? limit 1";
		$re=DB::select($sql,$values);
		$id=isset($re[0]) ? $re[0]['id'] : '';
		if($id){
			$sql="update pt_keyword_video_comment_all set ";
			foreach($data as $k=>$v){
				$sql.="`{$k}`='{$v}',";
			}
			$sql=substr($sql,0,-1)." where id={$id}";
			DB::update($sql);
		}else{
			$data['video_id']=$video_id;
			$data['comment_id']=$comment_id;
			DB::table("pt_keyword_video_comment_all")->insertGetId($data);
		}
	}
	
	//插入关键词筛选后的评论
	function saveVideoComment($data,$video_id,$comment_id){
		$values=[$video_id,$comment_id];
		$sql="select id from pt_keyword_video_comment where video_id = ? and comment_id = ? limit 1";
		$re=DB::select($sql,$values);
		$id=isset($re[0]) ? $re[0]['id'] : '';
		if($id){
			$sql="update pt_keyword_video_comment set ";
			foreach($data as $k=>$v){
				$sql.="`{$k}`='{$v}',";
			}
			$sql=substr($sql,0,-1)." where id={$id}";
			DB::update($sql);
		}else{
			$data['video_id']=$video_id;
			$data['comment_id']=$comment_id;
			DB::table("pt_keyword_video_comment")->insertGetId($data);
		}
	}
	
	//查询关键词视频的id
	function videoIdAll(){
		$time=date('Y-m-d',(time()-24*3600));
		$values=[$time];
		$sql="select video_id,keyword,title from pt_keyword_video where update_time >= ? order by update_time asc";
		$re=DB::select($sql,$values);
		return (isset($re[0]) ? $re : false);
	}
	
	
	//接口日志记录
	function api_msg($data){
		DB::table("pt_api_msg")->insertGetId($data);
	}
	
	//查询指定视频-----先去重复的 open_id
	function examineVideo(){
		$sql="select open_id from pt_dy_user_video where 1 = ? and (status=1 or status=2) group by open_id";
		$re=DB::select($sql,[1]);
		return (isset($re[0]) ? $re : false);
	}
	//查询指定 open_id 的视频数据集
	function findVideo($open_id){
		$sql="select item_id from pt_dy_user_video where open_id = ? and (status=1 or status=2)";
		$re=DB::select($sql,[$open_id]);
		return (isset($re[0]) ? $re : false);
	}
	
	//查询指定 open_id 的授权信息
	function oneTokenInfo($open_id){
		$sql="select access_token,refresh_token,open_id from pt_dy_access_token where status=1 and open_id = ?";
		$re=DB::select($sql,[$open_id]);
		return (isset($re[0]) ? $re[0] : false);
	}
	
	//更新视频数据
	function upVideoInfo($data,$item_id){
		$sql="update pt_dy_user_video set ";
		foreach($data as $k=>$v){
			$sql.="`{$k}`='{$v}',";
		}
		$sql=substr($sql,0,-1)." where item_id='{$item_id}'";
		DB::update($sql);
	}

    //更新同城视频数据
    function upExpVideoInfo($data,$item_id){
        $sql="update pt_exp_dyv set ";
        foreach($data as $k=>$v){
            $sql.="`{$k}`='{$v}',";
        }
        $sql=substr($sql,0,-1)." where item_id='{$item_id}'";
        DB::update($sql);
    }
	
	
}